package com.beauty.product.controller;

import com.beauty.product.dto.FileUploadResponse;
import com.beauty.product.dto.ProductImageDto;
import com.beauty.product.result.Result;
import com.beauty.product.service.FileStorageService;
import com.beauty.product.service.ProductService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/product/{productId}/image-upload")
@RequiredArgsConstructor
@Slf4j
public class ProductImageUploadController {

    private final FileStorageService fileStorageService;
    private final ProductService productService;

    @PostMapping
    public Result<ProductImageDto> uploadProductImage(
            @PathVariable String productId,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "isMain", defaultValue = "false") boolean isMain) {
        
        log.info("【商品服务】接收到商品[{}]图片上传请求, 是否主图:{}", productId, isMain);
        
        String fileName = fileStorageService.storeFile(file);
        
        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/api/product/images/download/")
                .path(fileName)
                .toUriString();
        
        ProductImageDto imageDto = new ProductImageDto();
        imageDto.setProductId(productId);
        imageDto.setImageUrl(fileDownloadUri);
        imageDto.setMain(isMain);
        
        ProductImageDto savedImage = productService.addProductImage(productId, imageDto);
        log.info("【商品服务】商品图片上传成功: imageId={}", savedImage.getId());
        
        return Result.success(savedImage);
    }

    @PostMapping("/batch")
    public Result<List<ProductImageDto>> uploadMultipleProductImages(
            @PathVariable String productId,
            @RequestParam("files") MultipartFile[] files) {
        
        log.info("【商品服务】接收到商品[{}]批量图片上传请求, 数量:{}", productId, files.length);
        
        List<ProductImageDto> uploadedImages = new ArrayList<>();
        
        Arrays.stream(files).forEach(file -> {
            String fileName = fileStorageService.storeFile(file);
            
            String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/api/product/images/download/")
                    .path(fileName)
                    .toUriString();
                    
            ProductImageDto imageDto = new ProductImageDto();
            imageDto.setProductId(productId);
            imageDto.setImageUrl(fileDownloadUri);
            imageDto.setMain(false); // 批量上传默认都不是主图
            
            ProductImageDto savedImage = productService.addProductImage(productId, imageDto);
            uploadedImages.add(savedImage);
        });
        
        log.info("【商品服务】商品批量图片上传成功, 上传数量:{}", uploadedImages.size());
        return Result.success(uploadedImages);
    }

    @GetMapping
    public Result<List<ProductImageDto>> getProductImageList(@PathVariable String productId) {
        log.info("【商品服务】获取商品[{}]的图片列表", productId);
        
        List<ProductImageDto> images = productService.getProductImages(productId);
        log.info("【商品服务】获取商品图片成功, 图片数量:{}", images.size());
        
        return Result.success(images);
    }

    @PutMapping("/{imageId}/main")
    public Result<ProductImageDto> setMainImage(
            @PathVariable String productId,
            @PathVariable Long imageId) {
        
        log.info("【商品服务】设置商品[{}]的主图, imageId:{}", productId, imageId);
        
        // 获取当前产品的所有图片
        List<ProductImageDto> images = productService.getProductImages(productId);
        
        // 找到目标图片
        ProductImageDto targetImage = images.stream()
                .filter(img -> img.getId().equals(imageId))
                .findFirst()
                .orElseThrow(() -> new RuntimeException("图片不存在: " + imageId));
        
        // 将目标图片设为主图，其他取消主图状态
        for (ProductImageDto img : images) {
            if (img.getId().equals(imageId)) {
                img.setMain(true);
                productService.updateProductImage(img);
            } else if (img.isMain()) {
                img.setMain(false);
                productService.updateProductImage(img);
            }
        }
        
        log.info("【商品服务】设置主图成功");
        return Result.success(targetImage);
    }

    @DeleteMapping("/{imageId}")
    public Result<Void> deleteProductImage(
            @PathVariable String productId,
            @PathVariable Long imageId) {
        
        log.info("【商品服务】删除商品[{}]的图片, imageId:{}", productId, imageId);
        
        // 获取当前图片信息
        ProductImageDto imageDto = productService.getProductImage(imageId);
        
        // 从数据库中删除图片记录
        productService.deleteProductImage(imageId);
        
        // 从文件系统中删除图片文件（如果存在）
        String imageUrl = imageDto.getImageUrl();
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
        try {
            fileStorageService.deleteFile(fileName);
        } catch (Exception e) {
            log.warn("【商品服务】删除图片文件失败: {}", e.getMessage());
        }
        
        log.info("【商品服务】删除商品图片成功");
        return Result.success();
    }
} 